package com.sohu.peak.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import com.sohu.peak.gallery.domain.Pic;

import java.util.regex.*;

import org.apache.commons.lang.StringUtils;

public class PicFileUtil {

	private static final Logger log = new Logger();

	/***************************************************************************
	 * @param oldPic
	 *            ԭʼͼƬ��ַ
	 * @param newPic
	 *            ��ͼƬ��ַ
	 * @param smallNewPic
	 *            ��ɵ�����ͼ��ַ
	 * @param middleNewPic
	 *            ��ɵ��е�ͼ��ַ
	 * @param wmk
	 *            �Ƿ����ˮӡ
	 * @param wmloc
	 *            ˮӡλ��
	 * @param wmtnp
	 *            ˮӡ͸����
	 **************************************************************************/
	public static boolean rebuildPic(String oldPic, String newPic,
			String smallNewPic, String middleNewPic, boolean wmk, String wmloc,
			String wmtnp) {
		boolean result = Boolean.TRUE;
		Process px;
		if (wmk) {// ��ˮӡ
			if (wmloc.equals("double")) {

				try {
					px = Runtime
							.getRuntime()
							.exec(
									"/usr/local/bin/composite -dissolve 100% -gravity northwest /ITC/sip-auto/HEAD/SIP-AUTO/WebRoot/images/wm2a.png "
											+ oldPic + " " + "a_" + oldPic);

					px.waitFor();
					px = Runtime
							.getRuntime()
							.exec(
									"/usr/local/bin/composite -dissolve 100% -gravity southeast /ITC/sip-auto/HEAD/SIP-AUTO/WebRoot/images/wm2b.png "
											+ "a_" + oldPic + " " + newPic);
					px.waitFor();

				} catch (IOException e) {
					e.printStackTrace();
					return Boolean.FALSE;
				} catch (InterruptedException e) {
					e.printStackTrace();
					return Boolean.FALSE;
				}
			} else {
				try {
					px = Runtime
							.getRuntime()
							.exec(
									"/usr/local/bin/composite -dissolve "
											+ wmtnp
											+ "% -gravity "
											+ wmloc
											+ " /ITC/sip-auto/HEAD/SIP-AUTO/WebRoot/images/wm.png "
											+ oldPic + " " + newPic);
					px.waitFor();
				} catch (IOException e) {
					log.error("rebuildPic error 1:" + e);
					e.printStackTrace();
					return Boolean.FALSE;
				} catch (InterruptedException e) {
					log.error("rebuildPic error 2:" + e);
					e.printStackTrace();
					return Boolean.FALSE;
				}

			}
		}

		// �������ͼ
		try {
			px = Runtime.getRuntime().exec(
					"/usr/local/bin/convert -geometry 120x90 " + oldPic + " "
							+ smallNewPic);
			px.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
			return Boolean.FALSE;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return Boolean.FALSE;
		}

		// ����е�ͼ
		try {
			px = Runtime.getRuntime().exec(
					"/usr/local/bin/convert -geometry 500 " + newPic + " "
							+ middleNewPic);
			px.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
			return Boolean.FALSE;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return Boolean.FALSE;
		}

		return result;
	}

	/**
	 * @param filePath
	 *            ���ѹ�ļ�ȫ·����
	 * @param datPath
	 *            ��ѹĿ��Ŀ¼·��
	 * @return List ��ѹ���ļ�ȫĿ¼�б�
	 */
	public static List<String> unzip(String filePath, String dstPath, byte[] buf) {
		return  PicFileUtil.unzip(filePath,dstPath);
	}

	public static String getFileExt(String fileName) {
		if (fileName == null)
			return "";
		int i = fileName.lastIndexOf(".");
		if (i < 0)
			return "";
		return fileName.substring(i + 1);

	}

	public static String[] removeSame(String[] arry) {

		Set<String> set = new LinkedHashSet<String>();
		for (int i = 0; i < arry.length; i++) {
			set.add(arry[i]);
		}

		return set.toArray(arry);

	}

	public static String getPicUrlInfo(Pic tmpPic) {
		String doc1 = ((tmpPic.getId() % 100) >= 10) ? tmpPic.getId() % 100
				+ "" : "0" + tmpPic.getId() % 100;
		String doc2 = ((tmpPic.getId() % 10000) / 100 >= 10) ? (tmpPic.getId() % 10000)
				/ 100 + ""
				: "0" + (tmpPic.getId() % 10000) / 100;

		return doc1 + File.separator + doc2 + File.separator;

	}

	public static boolean creatEmptyFile(String fileFulName) {
		try {
			File file = new File(fileFulName);
			if (file.exists())
				file.delete();
			file = new File(fileFulName);
			return file.createNewFile();

		} catch (IOException e) {
			return Boolean.FALSE;
		}
	}

	public static int[] GetNewWidth(float width, float height, float orderW,
			float orderH) {

		float newWidth = width;
		float newHeight = height;

		float newRate = 1;

		while (newHeight > orderH || newWidth > orderW) {

			if (newRate < (newWidth / orderW))
				newRate = (newWidth / orderW);
			else
				newRate = newHeight / orderH;

			newHeight = newHeight / newRate;
			newWidth = newWidth / newRate;

			if (newWidth > orderW) {
				log.debug("here");
				newRate = (newWidth / orderW);
				newWidth = newWidth / newRate;
				newHeight = newHeight / newRate;
			}

			if (newHeight > orderH) {
				log.debug("go");
				newRate = (newHeight / orderH);
				newWidth = newWidth / newRate;
				newHeight = newHeight / newRate;
			}

		}

		float style = newWidth / newHeight;

		int styleInt = 0;

		if (style >= 0.875 && style <= 1.14)
			styleInt = 0; // ��
		else if (style > 1)
			styleInt = 1; // ��
		else
			styleInt = 2; // ��

		int[] result = { (new Float(newWidth)).intValue(),
				(new Float(newHeight)).intValue(), styleInt };

		return result;

	}

	public static List<String> unzip(String zipFileName, String outputDirectory){
		List<String> result = new ArrayList<String>();
		try {
			org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(
					zipFileName);
			java.util.Enumeration e = zipFile.getEntries();
			org.apache.tools.zip.ZipEntry zipEntry = null;
			while (e.hasMoreElements()) {
				zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
				log.debug("name==="+zipEntry.getName());
				if (zipEntry.isDirectory()) {
					String name = zipEntry.getName();
					name = name.substring(0, name.length() - 1);
					log.debug("it's a dir��" + outputDirectory
							+ File.separator + name);
					File f1 = new File(outputDirectory);
					f1.mkdir();
					File f = new File(outputDirectory  + name);
					f.mkdir();
					log.debug("mkdir:" + outputDirectory
							+ File.separator + name);
				} else {
					File f = new File(outputDirectory
							+ zipEntry.getName());
					new File(outputDirectory + zipEntry.getName()).getParentFile().mkdirs();
					
					result.add(outputDirectory 
							+ zipEntry.getName());
					f.createNewFile();
					InputStream in = zipFile.getInputStream(zipEntry);
					FileOutputStream out = new FileOutputStream(f);
					int c;
					byte[] by = new byte[1024];
					while ((c = in.read(by)) != -1) {
						out.write(by, 0, c);
					}
					out.close();
					in.close();
				}
			}
		} catch (Exception ex) {
		}
		return result;
	}
	
	/*
	 * �ַ��Ƿ�����ģ��Ƿ���true���񷵻�false
	 * author �����
	 */
	public static boolean IsStrContainsChinese(String str)
	{
		String regEx = "[\u4e00-\u9fa5]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		if(m.find()) 
			return true;
		else 
			return false;
	}
	
	/*
	 * ȡ���ļ�������չ��filename��·�������չ��
	 * author �����
	 */
	public static String getFileName(String fileName) {
		if (fileName == null)
			return "";
		int i = fileName.lastIndexOf(".");
		int j = fileName.lastIndexOf("/");
		if (i < 0 || j < 0)
			return "";
		return fileName.substring(j+1,i);
	}
	
	/*
	 * ȡ���ļ�����չ��filename��·�������չ��
	 * author �����
	 */
	public static String getFileNameIncludeExt(String fileName) {
		if (fileName == null)
			return "";
		int j = fileName.lastIndexOf("/");
		if (j < 0)
			return fileName;
		return fileName.substring(j+1);
	}
	
	/*
	 * @author RuilinCao
	 * @param fileName
	 * @return ����ȥ��ո���ַ�
	 */
	public static String ignoreSpace(String fileName){
		return fileName.replaceAll("\\s", "");
	}
	/*
	 * �������ļ�����
	 * @author RuilinCao
	 * @param fileName �ļ����
	 * @return �������������ļ����
	 */
	public static String  reNameFile(String fileName){
		File srcFile = new File(fileName);
		String destName = srcFile.getName();
		String path = srcFile.getParent();
		path = path == null ? "" : path;
		destName = StringUtils.remove(destName, ' ');		
		File destFile = new File(new StringBuilder(path).append(File.separatorChar).append(destName).toString());
		srcFile.renameTo(destFile);
		return destFile.getAbsolutePath();
	}
	public static void main(String[] args) throws Exception {
//		List<String> fileList = PicFileUtil.unzip("D:/John/My Pictures/My Pictures.zip", "d:/old/");
//		for (String fn : fileList) {
//			log.debug(fn);
//		}
//
	
	}

}
